package cn.sightsnow.zh.controller;

import cn.sightsnow.zh.entity.Route;
import cn.sightsnow.zh.service.RouteService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Api(tags = "路径管理")
@RestController
@RequestMapping("/routes")
@Slf4j
public class RouteController {

    private final RouteService routeService;

    public RouteController(RouteService routeService) {
        this.routeService = routeService;
    }

    @ApiOperation("查询路径列表（可按状态过滤）")
    @GetMapping
    public List<Route> getRoutes(@RequestParam(required = false) Integer status) {
        return routeService.findRoutesByStatus(status);
    }

    @ApiOperation("新增路径（可指定ID）")
    @PostMapping
    public Route createRoute(@RequestBody Route route) {
        validateRouteStatus(route.getStatus());
        return routeService.createRoute(route);
    }

    @ApiOperation("更新路径（可设置结束时间）")
    @PutMapping("/{routeId}")
    public Route updateRoute(
            @PathVariable String routeId,
            @RequestBody Route route) {
        if (!routeId.equals(route.getRouteId())) {
            throw new ResponseStatusException(
                    HttpStatus.BAD_REQUEST, "路径ID不匹配");
        }
        return routeService.updateRoute(route);
    }



    @ApiOperation("删除路径")
    @DeleteMapping("/{routeId}")
    public void deleteRoute(@PathVariable String routeId) {
        routeService.deleteRoute(routeId);
    }

    @ApiOperation("获取路径详情")
    @GetMapping("/{routeId}")
    public Route getRouteDetail(@PathVariable String routeId) {
        Optional<Route> route = routeService.getRouteById(routeId);
        return route.orElseThrow(() -> new ResponseStatusException(
                HttpStatus.NOT_FOUND, "路径不存在"));
    }

    private void validateRouteStatus(Integer status) {
        if (status != 0 && status != 1) {
            throw new ResponseStatusException(
                    HttpStatus.BAD_REQUEST, "状态值必须是0或1");
        }
    }


}
